package com.wpw.java8demo;

import java.util.*;
import java.util.stream.Collectors;

import org.junit.Before;
import org.junit.Test;

public class CollectorTest {

	List<Apple> appList;
	String[] colors = {"red","green","yellow"};
	
	@Before
	public void before() {	
		appList = new ArrayList<>();
		Apple app;
		for (int i = 0; i < 20; i++) {
			app = new Apple();
			app.setColor(colors[i%3]);
			app.setWeigth(new Random().nextInt(10));
			appList.add(app);
		}
	}
	
	@Test
	public void test1() {
		Map<String, List<Apple>> collect = appList.stream()
			.collect(Collectors.groupingBy(Apple::getColor));
		System.out.println(collect);
	}
	
	@Test
	public void test2() {
		//汇总
		Long count = appList.stream()
			.collect(Collectors.counting());
		System.out.println(count);
		
		//最大值
		Optional<Apple> maxWeigthApple = appList.stream()
			.collect(Collectors.maxBy(Comparator.comparing(Apple::getWeigth)));
		System.out.println(maxWeigthApple.get());
		
		//最小值
		Optional<Apple> minWeigthApple = appList.stream()
			.collect(Collectors.minBy(Comparator.comparing(Apple::getWeigth)));
		System.out.println(minWeigthApple.get());
		
		//总和
		Long allWeigth = appList.stream()
			.collect(Collectors.summingLong(Apple::getWeigth));
		System.out.println(allWeigth);
		
		//平均值
		Double ave = appList.stream()
			.collect(Collectors.averagingInt(Apple::getWeigth));
		System.out.println(ave);

		IntSummaryStatistics sta = appList.stream()
				.collect(Collectors.summarizingInt(Apple::getWeigth));
		sta.getSum();
		sta.getAverage();
		sta.getMax();

		//连接字符存
		String join = appList.stream()
			.map(Apple::getColor)
			.collect(Collectors.joining(","));
		System.out.println(join);
	}
	
	@Test
	public void test3() {
		Integer sum = appList.stream()
				.collect(Collectors.reducing(0, Apple::getWeigth, Integer::sum));
		System.out.println(sum);

		Integer sum2 = appList.stream()
				.map(Apple::getWeigth)
				.collect(Collectors.reducing(0, Integer::sum));
		System.out.println(sum2);
		
		//性能最好，避免拆装箱
		int sum3 = appList.stream()
				.mapToInt(Apple::getWeigth)
				.sum();
			System.out.println(sum3);
		
		Optional<Apple> maxApple = appList.stream()
			.collect(Collectors.reducing((a1, a2) -> a1.getWeigth() > a2.getWeigth() ? a1 : a2));
		System.out.println(maxApple.get());
	}
	
	@Test
	public void test4() {
		Optional<String> reduce = appList.stream()
			.map(Apple::getColor)
			.reduce((a,b) -> a + "," + b);
		System.out.println(reduce.get());
	}
	
	
}
